package com.itheima.web.servlet;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.ResourceBundle;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.beanutils.BeanUtils;

import com.google.gson.Gson;
import com.itheima.domain.Cart;
import com.itheima.domain.CartItem;
import com.itheima.domain.Category;
import com.itheima.domain.Order;
import com.itheima.domain.OrderItem;
import com.itheima.domain.Pagebean;
import com.itheima.domain.Product;
import com.itheima.domain.User;
import com.itheima.service.ProductService;
import com.itheima.utils.CommonsUtils;
import com.itheima.utils.PaymentUtil;

public class ProductServlet extends BaseServlet {

	
	//获得我的订单
	public void myOrders(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = request.getSession();
		//判断用户是否已经登录 未登录下面代码不执行
		User user = (User) session.getAttribute("user");
		
		if(user==null){
			//没有登录
			response.sendRedirect(request.getContextPath()+"/login.jsp");
			return;
		}
		ProductService service = new ProductService();
		//查询该用户的所有的订单信息（单表查询orders表）
		//集合中 的每一个order对象的数据是不完整的 缺少List<OrderItem> orderItems
		List<Order> orderList = service.findAllOrders(user.getUid());
		
		//循环所有的订单，为每个订单填充订单项集合信息
		if(orderList!=null){
			for (Order order : orderList) {
				//获得每个订单的oid
				String oid =order.getOid();
				//查询该订单的所有的订单项--mapList封装的是多个订单项和该订单项中的商品信息
				List<Map<String, Object>> mapList =service.findAllOrderItemByOid(oid);
				//mapList转换成List<OrderItem> orderItems
				for (Map<String, Object> map : mapList) {
					
					try {
						//从map中取出count subtotal封装到OrderItem中
						OrderItem item =new OrderItem();
						//item.setCount(Integer.parseInt(map.get("count").toString()));
						BeanUtils.populate(item, map);
						//从map中取出pimage pname shop_price封装到product中
						Product product =new Product();
						BeanUtils.populate(product, map);
						//将product封装到orderItem
						item.setProduct(product);
						//将orderitem封装到order中的orderItemList中
						order.getOrderItems().add(item);
					} catch (IllegalAccessException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (InvocationTargetException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					
				}
				
			}
		}
		//orderList封装完整
		request.setAttribute("orderList", orderList);
		
		request.getRequestDispatcher("/order_list.jsp").forward(request, response);
	}
	//显示商品的类别的功能
	public void categoryList(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		ProductService service =new	ProductService();
		//准备分类数据
				List<Category> categoryList = service.findAllCategory();
				Gson gson =new Gson();
				String json = gson.toJson(categoryList);
				response.setContentType("text/html;charset=UTF-8");
				response.getWriter().write(json);
	}
	
	//显示首页的功能IndexServlet
	public void index(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		ProductService service = new ProductService();
		//准备热门商品
		List<Product> hotProductList = service.findHotProductList();
		//准备最新商品
		List<Product> newProductList =service.findNewProductList();
		
		//准备分类数据
		List<Category> categoryList = service.findAllCategory();
		request.setAttribute("hotProductList", hotProductList);
		request.setAttribute("newProductList", newProductList);
		request.setAttribute("categoryList", categoryList);
		
		request.getRequestDispatcher("/index.jsp").forward(request, response);
	}
	
	//显示商品详细信息
	public void productInfo(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//获得当前页
				String currentPage = request.getParameter("currentPage");
				//获得商品类别
				String cid = request.getParameter("cid");
				
				//获得要查询的商品的pid
				String pid = request.getParameter("pid");
				
				ProductService service = new ProductService();
				Product product = service.findProductByPid(pid);
				
				request.setAttribute("product", product);
				request.setAttribute("currentPage", currentPage);
				request.setAttribute("cid", cid);
				//获得客户端cookie---获得名字是pids的cookie；
				String pids=pid;
				Cookie[] cookies= request.getCookies();
				if(cookies!=null){
					for(Cookie cookie:cookies){
						if("pids".equals(cookie.getName())){
							pids =cookie.getValue();
								//1-3-2本次访问的pid是8---->8-1-3-2
								//1-3-2本次访问的pid是3---->3-1-2
								//将pids拆成一个数组
								String[] split =pids.split("-"); //{3,1,2}
							List<String> asList = Arrays.asList(split);//[3,1,2]
							LinkedList<String> list = new LinkedList<String>(asList);//[3,1,2]
							//判断集合中是否存在当前pid
							if(list.contains(pid)){
								//包含当前查看商品的pid
								list.remove(pid);
							}
								list.addFirst(pid);
								//将[3,1,2]转换成3-1-2字符串
								StringBuffer sb =new StringBuffer();
								for(int i=0;i<list.size();i++){
									sb.append(list.get(i));
									sb.append("-");//3-1-2-
								}
								
								//去掉3-1-2-后的-
								pids =sb.substring(0,sb.length()-1);
								
								
						}
					}
				}
				
				//转发之前，创建cookie存储pid；
				Cookie cookie_pids = new Cookie("pids", pids);
				response.addCookie(cookie_pids);
				
				
				request.getRequestDispatcher("product_info.jsp").forward(request, response);
	}
	
	//显示商品的类别获得商品的列表
	public void productList(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//获得cid
		String cid = request.getParameter("cid");
		
		String currentPageStr = request.getParameter("currentPage");
		if(currentPageStr==null) currentPageStr="1";
		int currentPage = Integer.parseInt(currentPageStr);
		int currentCount=12;
		ProductService service =new ProductService();
		Pagebean pagebean= service.findProductListByCid(cid,currentPage,currentCount);
		request.setAttribute("pagebean", pagebean);
		request.setAttribute("cid", cid);
		//定义一个集合 记录历史商品信息的集合
		List<Product> historyProductList =new ArrayList<Product>();
		//获取客户端携带名字叫pids的cookie
				Cookie[] cookies =request.getCookies();
				if(cookies!=null){
				for (Cookie cookie : cookies) {
					if("pids".equals(cookie.getName())){
						String pids = cookie.getValue();//3-2-1
						String[] split = pids.split("-");
						for (String pid : split) {
							Product pro = service.findProductByPid(pid);
							historyProductList.add(pro);
						}
					}
				}
				}
				//将历史记录的集合放到域中
				request.setAttribute("historyProductList", historyProductList);
		request.getRequestDispatcher("/product_list.jsp").forward(request, response);
	}
	
	//将商品添加到购物车中addProductToCart
	public void addProductToCart(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = request.getSession();
		ProductService service =new	ProductService();
		//获得要放到购物车商品的pid
		String pid = request.getParameter("pid");
		//获得该商品的购买数量
		int buyNum = Integer.parseInt(request.getParameter("buyNum"));
		
		Product product = service.findProductByPid(pid);
		//计算小计
		double subtotal = product.getShop_price()*buyNum;
		//封装CartItem
		CartItem item = new CartItem();
		item.setProduct(product);
		item.setBuyNum(buyNum);
		item.setSubtotal(subtotal);
		//获得购物车----判断是否在session中已经存在购物车
		Cart cart =(Cart) session.getAttribute("cart");
		if(cart==null){
			cart=new Cart();
		}
		//将购物项放到车中
		//先判断购物车中是否已将包含此购物项了   判断key是否已存在
		//如果购物车中已经存在该商品-----将现在买的数量与原有的数量进行相加操作
		Map<String, CartItem> cartItems = cart.getCartItems();
		double newsubtotal =0;
		if(cartItems.containsKey(pid)){
			//取出原有商品的数量
			CartItem cartItem = cartItems.get(pid);
			int oldBuyNum = cartItem.getBuyNum();
			oldBuyNum+=buyNum;
			cartItem.setBuyNum(oldBuyNum);
			cart.setCartItems(cartItems);
			
			//修改小计
			double oldsubtotal = cartItem.getSubtotal();
			newsubtotal = buyNum*product.getShop_price();
			cartItem.setSubtotal(oldsubtotal+newsubtotal);
			//cartItem.setSubtotal(oldBuyNum*product.getShop_price());
			
		}else{
			//如果车中没有该商品
			cartItems.put(pid, item);
			newsubtotal = buyNum*product.getShop_price();
		}
		
		//计算总计
		double total = cart.getTotal()+newsubtotal;
		cart.setTotal(total);
		//将车再次放回session
		session.setAttribute("cart", cart);
		
		//转发存在问题
		//request.getRequestDispatcher("/cart.jsp").forward(request, response);
		response.sendRedirect(request.getContextPath()+"/cart.jsp");
	}
	
	//delProFromCart删除单一商品
	public void delProFromCart(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//获得要删除的item的pid
		String pid = request.getParameter("pid");
		//删除session中的购物车中的购物项集合中的item
		HttpSession session = request.getSession();
		Cart cart = (Cart) session.getAttribute("cart");
		if(cart!=null){
			Map<String, CartItem> cartItems = cart.getCartItems();
			//需要修改总价
			cart.setTotal(cart.getTotal()-cartItems.get(pid).getSubtotal());
			cartItems.remove(pid);
			cart.setCartItems(cartItems);
			
		}
		session.setAttribute("cart", cart);
		response.sendRedirect(request.getContextPath()+"/cart.jsp");
		
	}
	//提交订单submitOrder
	public void submitOrder(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = request.getSession();
		//判断用户是否已经登录 未登录下面代码不执行
		User user = (User) session.getAttribute("user");
		
		if(user==null){
			//没有登录
			response.sendRedirect(request.getContextPath()+"/login.jsp");
			return;
		}
		//封装好一个Order对象 传递给service层
		Order order=new Order();
		String oid =CommonsUtils.getUUID();
		order.setOid(oid);
		
		Date date=new Date(); 
		SimpleDateFormat temp=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
		String date2=temp.format(date); 
		Date date3 = null;
		try {
			date3 = temp.parse(date2);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		order.setOrdertime(date3);


		//order.setOrdertime(new Date());
		
		//获得session中的购物车
		Cart cart =(Cart) session.getAttribute("cart");
		double total = cart.getTotal();
		order.setTotal(total);
		
		order.setState(0);
		
		order.setAddress(null);
		order.setName(null);
		order.setTelephone(null);
		
		order.setUser(user);
		
		//获得购物车中的购物项集合map
		Map<String, CartItem> cartItems = cart.getCartItems();
		for (Map.Entry<String,CartItem> entry : cartItems.entrySet()) {
			CartItem cartItem =entry.getValue();
			OrderItem orderItem =new OrderItem();
			orderItem.setItemid(CommonsUtils.getUUID());//id
			orderItem.setCount(cartItem.getBuyNum());//购买数量
			orderItem.setSubtotal(cartItem.getSubtotal());//小计
			orderItem.setProduct(cartItem.getProduct());
			orderItem.setOrder(order);
			
			//将该订单项添加到订单的订单项集合中
			order.getOrderItems().add(orderItem);
		}
		ProductService service =new ProductService();
		service.submitOrder(order);
		
		session.setAttribute("order", order);
		
		//页面跳转
		response.sendRedirect(request.getContextPath()+"/order_info.jsp");
	}
	
	//确认订单--更新收货人+在线支付  confirmOrder
	public void confirmOrder(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//1更新收货人信息
		Map<String, String[]> properties = request.getParameterMap();
		Order order = new Order();
		try {
			BeanUtils.populate(order, properties);
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		ProductService service =new ProductService();
		service.updateOrderAddr(order);
		//2.在线支付
		//获得选择的银行
//		String pd_FrpId =request.getParameter("pd_FrpId");
//		if(pd_FrpId.equals("ICBC-NET-B2C")){
//			
//		}
		
		//接入第三方支付平台，易宝支付
		// 获得 支付必须基本数据
				String orderid = request.getParameter("oid");
				//String money = order.getTotal()+"";
				String money = "0.01";
				// 银行
				String pd_FrpId = request.getParameter("pd_FrpId");

				// 发给支付公司需要哪些数据
				String p0_Cmd = "Buy";
				String p1_MerId = ResourceBundle.getBundle("merchantInfo").getString("p1_MerId");
				String p2_Order = orderid;
				String p3_Amt = money;
				String p4_Cur = "CNY";
				String p5_Pid = "";
				String p6_Pcat = "";
				String p7_Pdesc = "";
				// 支付成功回调地址 ---- 第三方支付公司会访问、用户访问
				// 第三方支付可以访问网址
				String p8_Url = ResourceBundle.getBundle("merchantInfo").getString("callback");
				String p9_SAF = "";
				String pa_MP = "";
				String pr_NeedResponse = "1";
				// 加密hmac 需要密钥
				String keyValue = ResourceBundle.getBundle("merchantInfo").getString(
						"keyValue");
				String hmac = PaymentUtil.buildHmac(p0_Cmd, p1_MerId, p2_Order, p3_Amt,
						p4_Cur, p5_Pid, p6_Pcat, p7_Pdesc, p8_Url, p9_SAF, pa_MP,
						pd_FrpId, pr_NeedResponse, keyValue);
				
				
				String url = "https://www.yeepay.com/app-merchant-proxy/node?pd_FrpId="+pd_FrpId+
								"&p0_Cmd="+p0_Cmd+
								"&p1_MerId="+p1_MerId+
								"&p2_Order="+p2_Order+
								"&p3_Amt="+p3_Amt+
								"&p4_Cur="+p4_Cur+
								"&p5_Pid="+p5_Pid+
								"&p6_Pcat="+p6_Pcat+
								"&p7_Pdesc="+p7_Pdesc+
								"&p8_Url="+p8_Url+
								"&p9_SAF="+p9_SAF+
								"&pa_MP="+pa_MP+
								"&pr_NeedResponse="+pr_NeedResponse+
								"&hmac="+hmac;

				//重定向到第三方支付平台
				response.sendRedirect(url);
	}
	
	//清空购物车clearCart
	public void clearCart(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = request.getSession();
		session.removeAttribute("cart");
		response.sendRedirect(request.getContextPath()+"/cart.jsp");
	}
}